package com.sali.design_pattern.h_proxy_pattern.lesson_03_02;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @description:
 * @author: zhang hang
 * @date: 2023/3/19 22:11.
 * @version: 1.0
 */
public class LogProxy implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before();
        Object invoke = methodProxy.invokeSuper(obj, args);
        after();
        return null;
    }

    public Object getProxy(Class<?> clz) {
        Enhancer enhancer = new Enhancer();
        // 代理的目标对象
        enhancer.setSuperclass(clz);
        // 设置代理类 this = new LogProxy();
        enhancer.setCallback(this);
        // 生成代理对象
        return enhancer.create();
    }

    public void before() {
        System.out.println("鉴权...");
        System.out.println("限流...");
    }

    public void after() {
        System.out.println("保存日志...");
    }
}
